/**
 * Copyright (c) 2008, stauren.net All rights reserved.
 * YUI CN widget image cropper
 * @author stauren@stauren.net
 */

__.set('__.widget');
__.widget.imageCropper = (function() {
  var _ = __._, _config = {
      iSliderLeft : 147,
      maxRate : 2,
      minRate : 1,
      trackLength : 260,
      trackPreX : 13,
      windowX : 80,
      windowY : 80,
      canvasX : 300,
      canvasY : 300,
      initRate : 1,
      trackImg : 'http://double-underscore.googlecode.com/svn/trunk/img/image_crop_track.gif',
      sliderImg : 'http://double-underscore.googlecode.com/svn/trunk/img/image_crop_grip.gif'
 //     trackImg : 'image_crop_track.gif',
 //     sliderImg : 'image_crop_grip.gif'
    },
    _dImg, _dSliderHandler, _iWidth, _iHeight,
    _fOldRate, _dX, _dY, _fSliderX, _fnGetRate,
    _fnSetImg = function(rate) {
      var _ds = _dImg.style;
      _ds.width = _iWidth * rate + 'px';
      _ds.height = _iHeight * rate + 'px';

     // centralized zoom
     // _ds.left = [(_config.canvasX-rate*_iWidth)/2, 'px'].join('');
     // _ds.top = ['-', (_config.canvasY+rate*_iHeight)/2, 'px'].join('');

     // _ds.left = [(_xo+_config.canvasX*(_fOldRate-1)/2)*rate/_fOldRate+_config.canvasX/2*(1-rate), 'px'].join('');
     // _ds.top = ['-', _config.canvasY/2*(rate+1)+(_config.canvasY/2*(_fOldRate+1)+_yo)/_fOldRate*rate, 'px'].join('');
      _ds.left = _dX*rate+_config.canvasX/2*(1-rate) + 'px';
      _ds.top = _dY*rate + _config.canvasY/2*(rate-1) + 'px';
      _fOldRate = rate;
    },
    _fnOnOk = function(e){
      var winX = _config.windowX, winY = _config.windowY,
        x = parseInt(_dImg.style.left) - (_config.canvasX - winX)/2,
        y = parseInt(_dImg.style.top) + (_config.canvasY + winY)/2,
        oResult = {
          pointx : -x,
          pointy : -y,
          width : winX,
          height : winY,
          rate : _fOldRate.toFixed(3)
        };
          
      if (_config.postUrl) {
        _.p({
          sUrl : _config.postUrl,
          sPost : _.toJson(oResult),
          fnSuccess : function(s) {
            _.log(s);
          }
        });
      } else if (_config.callback) {
        _config.callback(oResult);
      }
    },
    _fnSliderMd = function(e){
      _.beginDrag(e, _dSliderHandler, false, {'t':0, 'r':_config.trackLength - _fSliderX + _config.trackPreX, 'b':0, 'l':_fSliderX}, false, 
        function(x,y,zone) {
          var _fPercent = _fnGetRate(x - zone.left);
          _fnSetImg(_fPercent);
        }
      );
    },
    _fnCanvasMd = function(e){
      _.beginDrag(e, _dImg, false, false, false, function(x,y,zone) {
        var _ds = _dImg.style, _xo = parseFloat(_ds.left, 10), _yo = parseFloat(_ds.top, 10);
        _dX = (_xo*2+_config.canvasX*(_fOldRate-1))/(2*_fOldRate);
        _dY = (_config.canvasY*(1-_fOldRate)+2*_yo)/(2*_fOldRate);
      });
    },
    _fnCreateEls = function(ct) {
      var oEls = {
        id : 'yn-cropper-ctn',
        css : 'font-size: 14px; font-family: Geneva,Lucida Sans,Lucida Grande,Lucida Sans Unicode,Verdana,sans-serif;',
        child : [{
          cls : 'canvas',
          css : 'width : 300px; height : 300px; border : 3px solid #CCC; overflow : hidden; position : relative; float : left;',
          child : [{
            tag : 'table',
            css : 'width : 100%; height : 100%; z-index : 9; opacity : 0.75; filter:alpha(opacity=75); cursor : move;',
            child : {
              tag : 'tbody',
              child : [
                { 
                  tag : 'tr',
                  child : {
                    tag : 'td',
                    attrs : { colSpan : '3'},
                    cls : 'yc-top',
                    css : 'height:110px;background-color:#646464;'
                  }
                },
                {
                  tag : 'tr',
                  child : [
                    {
                      tag : 'td',
                      css : 'width:110px;background-color:#646464;',
                      cls : 'yc-left'
                    },
                    {
                      tag : 'td',
                      css : 'width:1px;background-color:transparent;border:1px solid #FFF;',
                      cls : 'yc-window',
                      child : {
                        css : 'width:80px;height:80px;'
                      }
                    },
                    {
                      tag : 'td',
                      css : 'background-color:#646464;',
                      cls : 'yc-right'
                    }
                  ]
                },
                { 
                  tag : 'tr',
                  child : {
                    tag : 'td',
                    attrs : { colSpan : '3'},
                    cls : 'yc-bottom',
                    css : 'height:109px;background-color:#646464;'
                  }
                }
              ]
            }
          },
          {
            id : 'yc-ori-image',
            css : 'position:relative;top:0;left:0;z-index:-1;',
            child : {
              tag : 'img',
              css : 'position:relative;',
              attrs : { src : _config.sImgSrc }
            }
          }
          ]
        },
        {
          cls : 'tools',
          css : 'float:left;clear:left;',
          child : {
            tag : 'ul',
            child : [
              /*{
                tag : 'li',
                child : [
                  {
                    text : '剪切结果图片长宽：'
                  },
                  {
                    tag : 'input',
                    id : 'yn-cropper-width',
                    css : 'width:50px;',
                    attrs : { maxLength : 3}
                  },
                  {
                    text : ' X '
                  },
                  {
                    tag : 'input',
                    id : 'yn-cropper-width',
                    css : 'width:50px;',
                    attrs : { maxLength : 3}
                  }
                ]
              },*/
              {
                tag : 'li',
                child : {
                  css : 'height:18px;line-height:18px;',
                  child : [
                    {
                      cls : 'yn-slider',
                      css : 'background:url('+ _config.sliderImg +') no-repeat;position:relative;height:16px;line-height:16px;font-size:0;width:11px;display:inline;float:left;top:1px;'
                    },
                    {
                      tag : 'img',
                      cls : 'yn-track',
                      css : 'width:285px;height:18px;',
                      attrs : {src:_config.trackImg}
                    }
                  ]
                }
              },
              {
                tag : 'li',
                css : 'text-align:center',
                child : [
                  {
                    tag : 'input',
                    id : 'yn-cropper-ok',
                    css : 'width:50px;',
                    attrs : { type : 'submit', value : 'OK' }
                  }/*,
                  {
                    tag : 'input',
                    id : 'yn-cropper-cancel',
                    css : 'width:50px;',
                    attrs : { type : 'button', value : '取消' }
                  }*/
                ]
              }
            ]
          }
        }
        ]
      };
      _.addEl(oEls, ct);
    };

  return function(container, src,  config) {
    config = config == undefined ? {} : config;
    _.objExtend(_config, config);

    container = _.$(container)[0];
    _config.sImgSrc = src;

    if(!container || !src) {
      return false;
    }

    var newImg = new Image();
    _.on(newImg, 'load', function(){
      _fnCreateEls(container);

      _dImg = _.$('#yc-ori-image img')[0];
      _dSliderHandler = _.$('#yn-cropper-ctn .yn-slider')[0];
      _iWidth = _dImg.width;
      _iHeight = _dImg.height,
      _fOldRate = _config.initRate;

      // the min scale rate means the longer border fit the window
      _config.minRate = Math.min(_config.windowX/_iWidth, _config.windowY/_iHeight, 1);

      _fnGetRate = _.compose(_.curry('+', _config.minRate),
        _.curry('*', (_config.maxRate - _config.minRate) / _config.trackLength)),


      _dX = (_config.canvasX-_iWidth)/2;
      _dY = '-' + (_config.canvasY+_iHeight)/2;
      _fSliderX =  _config.trackLength / (_config.maxRate - _config.minRate) * (1 - _config.minRate);
      _dSliderHandler.style.left = _fSliderX + _config.trackPreX + 'px';

      _fnSetImg(_config.initRate, true);

      _.on(_.$('#yn-cropper-ctn .canvas')[0], 'mousedown', _fnCanvasMd);
      _.on(_dSliderHandler, 'mousedown', _fnSliderMd);
      _.on(_.$('yn-cropper-ok')[0], 'click', _fnOnOk);
    });
    newImg.src = src;
  }
})();
